function toTree(arr) {
  let res = [],
    map = {};
  for (let i = 0; i < arr.length; i++) {
    map[arr[i].id] = arr[i];
  }
  for (let i = 0; i < arr.length; i++) {
    let parent = map[arr[i].pid];
    if (parent) {
      (parent.children || (parent.children = [])).push(arr[i]);
    } else {
      res.push(arr[i]);
    }
  }
  return res;
}

const source = [
  {
    id: 1,
    pid: 0,
    name: "body",
  },
  {
    id: 2,
    pid: 1,
    name: "title",
  },
  {
    id: 3,
    pid: 2,
    name: "div",
  },
];

console.log(toTree(source));
